package yu.code.yurpc.spi;

import cn.hutool.core.io.resource.ResourceUtil;
import lombok.extern.slf4j.Slf4j;
import yu.code.yurpc.serializer.Serializer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 我的SPI 加载器（支持键值对映射）
 */
@Slf4j
public class MySpiLoader {
    //用于存放已经实例化对象
    private static final ConcurrentHashMap<String, Object> instanceMap = new ConcurrentHashMap<>();
    //用于存放所有的SPI扫描所有需要加载的全类名
    private static final ConcurrentHashMap<String, Map<String, Class<?>>> loaderMap = new ConcurrentHashMap<>();

    //默认自定义SPI路径
    private static final String CUSTOM_RPC_DIR = "META_INF/rpc/custom/";
    //默认系统SPI路径
    private static final String SYSTEM_RPC_DIR = "META_INF/rpc/system/";
    //扫描路径
    private static final String[] SCAN_DIRS = new String[]{SYSTEM_RPC_DIR, CUSTOM_RPC_DIR};
    //扫描的类
    //private static final Class<?>[] LOAD_CLASSES_LIST = new Class[]{Serializer.class};

    /*public static void loadAll() {
        log.info("加载所有 SPI");
        for (Class<?> aClass : LOAD_CLASSES_LIST) {
            load(aClass);
        }
    }*/

    public static Map<String, Class<?>> load(Class<?> loadClass) {
        log.info("加载 SPI:{}", loadClass.getName());
        //存放SPI扫描到的对应类的各种实现
        HashMap<String, Class<?>> keyClassMap = new HashMap<>();
        //扫描路径，用户自定义的 SPI 优先级高于系统 SPI
        for (String scanDir : SCAN_DIRS) {
            List<URL> resources = ResourceUtil.getResources(scanDir + loadClass.getName());
            for (URL resource : resources) {
                try {
                    InputStreamReader inputStreamReader = new InputStreamReader(resource.openStream());
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        String[] strArray = line.split("=");
                        if (strArray.length > 1) {
                            String key = strArray[0];
                            String className = strArray[1];
                            keyClassMap.put(key, Class.forName(className));
                        }
                    }
                } catch (Exception e) {
                    log.error("spi resource load error", e);
                }
            }
        }
        loaderMap.put(loadClass.getName(), keyClassMap);
        return keyClassMap;
    }

    public static <T> T getInstance(String key, Class<T> clazz) {
        //判断是否有该类型的SPI
        Map<String, Class<?>> keyClassMap = loaderMap.get(clazz.getName());
        if (keyClassMap == null) {
            throw new RuntimeException(String.format("SpiLoader 未找到 %s 类型", clazz.getName()));
        }
        //判断是否有该key
        if (!keyClassMap.containsKey(key)) {
            throw new RuntimeException(String.format("SpiLoader 的 %s 不存在 key=%s 的类型", clazz.getName(), key));
        }
        // 获取到要加载的实现类型
        //判断是否已经实例化
        if (!instanceMap.containsKey(clazz.getName())) {
            //还未实例化
            //获取对应key的实现类
            Class<?> aClass = keyClassMap.get(key);
            //实例化
            try {
                Object o = aClass.newInstance();
                //缓存实例化对象
                instanceMap.put(clazz.getName(), (T) o);
            } catch (InstantiationException | IllegalAccessException e) {
                log.error("实例化失败", e);
            }
        }
        return (T) instanceMap.get(clazz.getName());
    }
}
